import json
from collections import namedtuple

from flask_restful import Resource

from app.models import Image as ImageDocument
from app.models import Instance as DeploymentDocument
from app.resources.helpers import *


InstanceTuple = namedtuple('InstanceTuple', 'name url')


class Service(Resource):

    def get(self, suffix=None):
        return self.__get_service_with_api() if not suffix else \
                self.__get_service_instance(suffix)

    def __get_service_instance(self, service):
        instances = DeploymentDocument.objects(service=service,
                                               publish_status=True)
        return result_success(
            list(map(lambda x: InstanceTuple(x.name,
                     f'http://{x.name}.{x.namespace}:{x.port}')._asdict(),
                 instances)))

    # list all service(image) available, along with their API info
    def __get_service_with_api(self):
        # filter out images that haven't got published deployment
        image_names = set(map(lambda x: x.service, DeploymentDocument
                              .objects(publish_status=True)
                              .fields(service=1)))

        # TODO: make deployment save image's id instead of image's name so that
        # we can use image_id instead of name to compare here.
        documents = ImageDocument.objects(name__in=image_names) \
            .exclude('id')
        return result_success(
            json.loads(documents.to_json())
        )
